#!/usr/bin/perl

# ---------- Init variables -------
#my $version = "0.0001";
# ---------- external readable parameters -------
## Functions
##-------------------------------------------------------
#
# stict syntax checking.
use strict;
use CGI qw(param upload);
use SIM_settings;
use SIM_base;
use SIM_cgi;
use Text::Diff;

# Startupscript casetool, part of Sipman.

my $tool = $ARGV[0];
my $action = $ARGV[1];
my $option1 = $ARGV[2];
if ( "$option1" eq "none" ) {
  $option1 = "";
}
my $option2 = $ARGV[3];
if ( "$option2" eq "none" ) {
  $option2 = "";
}
my $option3 = $ARGV[4];


my $httpReF = $ENV{'HTTP_REFERER'};
my $httpScriptName = $ENV{'SCRIPT_NAME'};
my $systemHtml = $SIMparam{'SIMsystemHtmlDir'};
my %fileDir = ();
my %dirName = ();
my %editFile = ();
my %cmpFile = ();
my %uploadFile = ();
my %exportDir = ();
$fileDir{ 'MainConfig' } = $ENV{'SIM_MAINCONFD'} || die "Oops no env found for SIM_MAINCONFD.";
$dirName{ 'MainConfig' } = "Main config files.";
$editFile{ 'MainConfig' } = "no";
$fileDir{ 'SharedConfig' } = $ENV{'SIM_SHAREDCONFD'} || die "Oops no env found for SIM_SHAREDCONFD.";
$dirName{ 'SharedConfig' } = "Shared config files.";
$fileDir{ 'DomainConfig' } = $ENV{'SIM_CONFD'} || die "Oops no env found for SIM_CONFD.";
$dirName{ 'DomainConfig' } = "Domain specific config files.";
$fileDir{ 'SubnetTemplates' } = $ENV{'SIM_SUBNETTEMPL'} || die "Oops no env found for SIM_SUBNETTEMPL.";
$dirName{ 'SubnetTemplates' } = "Subnet template files.";
$fileDir{ 'NamedPtr' } = $ENV{'SIM_NAMEDPTRD'} || die "Oops no env found for SIM_NAMEDPTRD.";
$dirName{ 'NamedPtr' } = "DNS pointer files.";
$fileDir{ 'SipmanLog' } = $ENV{'SIM_LOGDIR'} || die "Oops no env found for SIM_LOGDIR.";
$dirName{ 'SipmanLog' } = "Logging directory for Sipman.";
$editFile{ 'SipmanLog' } = "no";
$fileDir{ 'Syslog' } = $ENV{'SIM_SYSLOGSYS'} || die "Oops no env found for SIM_SYSLOGSYS.";
$dirName{ 'Syslog' } = "Syslog directory.";
$editFile{ 'Syslog' } = "no";
$fileDir{ 'GraphReport' } = $SIMparam{'SIMgraphReportDir'} || die "Oops no env found for SIMgraphReportDir.";
$dirName{ 'GraphReport' } = "Graph reporting files.";
$fileDir{ 'ApacheLog' } = $ENV{'SIM_HTTPLOGDIR'} || die "Oops no env found for SIM_HTTPLOGDIR.";
$dirName{ 'ApacheLog' } = "Apache webserver logdir.";
$editFile{ 'ApacheLog' } = "no";
#$fileDir{ 'Named' } = $ENV{'SIM_NAMEDWORKD'} || die "Oops no env found for SIM_NAMEDWORKD.";
$fileDir{ 'Named' } = $ENV{'SIM_NAMEDD'} || die "Oops no env found for SIM_NAMEDWORKD.";
$dirName{ 'Named' } = "DNS zone file directory.";
$editFile{ 'Named' } = "no";
$fileDir{ 'Tftp' } = $ENV{'SIM_TFTPDIR'} || die "Oops no env found for SIM_TFTPDIR.";
$dirName{ 'Tftp' } = "Tftp directory.";
$uploadFile{ 'Tftp' } = "yes";
my $devConfDir = $ENV{'SIM_CONFIGD'} || die "Oops no env found for SIM_CONFIGD.";
$fileDir{ 'DevConfigsCurrent' } = "$devConfDir/current";
$dirName{ 'DevConfigsCurrent' } = "Current device configs.";
$editFile{ 'DevConfigsCurrent' } = "no";
$exportDir{ 'DevConfigsCurrent' } = "yes";
$fileDir{ 'DevConfigsHistory' } = "$devConfDir/history";
$dirName{ 'DevConfigsHistory' } = "History device configs.";
$editFile{ 'DevConfigsHistory' } = "no";
$cmpFile{ 'DevConfigsHistory' } = "yes";
$fileDir{ 'DevConfigsLogs' } = "$devConfDir/logs";
$dirName{ 'DevConfigsLogs' } = "Logging files for device config downloads.";
$editFile{ 'DevConfigsLogs' } = "no";

sub diffDir {
  my $dirPath = "@_[0]";
  my $subDir = "@_[1]";
# print("Running diff on $dirPath / $subDir.");
  my $workDir = $fileDir{ $dirPath };
  if ( "$subDir" ne "" ) {
    $workDir = "$fileDir{ $dirPath }/$subDir";
  }
  my ( $found, $first, $next, $last );
  if ( -d $workDir ) {
    chdir $workDir;
    my @dirList = reverse <*>;
    foreach my $entry (@dirList) {
      my $result = param($entry);
#     print("$entry, $result.<BR>");
      if ( "$result" eq "yes" ) {
        if ( "$last" eq "" ) {
          $found = "yes";
          $last = $entry;
        } else {
          $first = $entry;
        }
      } elsif (( "$last" ne "" ) and ( "$first" eq "" ) and ( "$next" eq "" )) {
        $next = $entry;
      }
    }
#   print("First: $first, next: $next, last: $last.<BR>");
    if ( "$last" eq "" ) {
      $last = $dirList[0];
      $first = $dirList[1];
    } elsif ( "$first" eq "" ) {
      $first = $next;
    }
    #&runCompare( $workDir, "context", $first, $last );
    &runCompare( $workDir, "table", $first, $last );
  }
}

sub compareAll {
  my $dirPath = "@_[0]";
  my $workDir = $fileDir{ $dirPath };
  my $dayCount = param('dayCount');
  if ( ! -d $workDir ) {
    print("Oops, no workdir found for $dirPath.");
  } elsif ( $dayCount eq "" ) {
    print("<FORM method=post Action=$httpScriptName?$tool+comp$dirPath>
          Select the numer of history day's:
	    <INPUT TYPE=text SIZE=2 NAME=dayCount VALUE=2>
            <INPUT TYPE=submit Value=\"Compare\">
	   </FORM>");
  } else {
    print("Comparing files in $dirPath<HR>");
    chdir $workDir;
    my @dirList = <*>;
    my $now = time;
    my $testTime = $dayCount * 86400;
    my $lastTest = $now - $testTime;
    foreach my $dirName (@dirList) {
      #print("Found $dirName.<HR>");
      if ( -d "$workDir/$dirName" ) {
#       print("Processing $dirName.<HR>");
	chdir( "$workDir/$dirName" );
	my @fileList = reverse <*>;
	my ($firstFile, $lastFile); 
	foreach my $fileName (@fileList) {
	  my $write_secs = (stat($fileName))[9];
          if ( "$firstFile" eq "" ) {
	    if ( $write_secs > $lastTest ) {
	      $firstFile = $fileName;
	    }
	  } else {
	    if ( $write_secs < $lastTest ) {
	      $lastFile = $fileName;
	      last;
	    }
	  }
	}
	#print("Found: $firstFile, $lastFile in $dirName.<BR>");
	if (( "$firstFile" ne "" ) and ( "$lastFile" ne "" )) {
	  &runCompare( "$workDir/$dirName" , "table", $lastFile, $firstFile);
	}
      }
    }
  }
}

sub runCompare {
  my $workDir = "@_[0]";
  my $compareType = "@_[1]";
  my $first = "@_[2]";
  my $last = "@_[3]";
  my $numLines = 5;
  if ( "$workDir" eq "" ) {
    $workDir = param('directory');
    $first = param('first');
    $last = param('last');
    $compareType = param('type');
    $numLines = param('numLines');
  }
  if ( ! -d $workDir ) {
    print("Oops, compare directory not found.");
  } else {
    print("<CENTER><TABLE><TR><TD>");
    &printDiffForm( $workDir, $first, $last, "$compareType", $numLines );
    print("</TD></TR></TABLE>");
    chdir $workDir;
    #print("Comparing: $first, to: $last, type: $compareType.");
    my @lines;
    if ( "$compareType" eq "unix" ) {
      @lines = ` diff -C $numLines $first $last `;
    } else {
      my $diff = diff "$first", "$last", { STYLE => "Context", CONTEXT => "$numLines"  };
      @lines = split( /\n/, $diff);
    }
    if (( "$compareType" eq "unix" ) or ( "$compareType" eq "context" )) {
      print("<TABLE><TR><TD><PRE>");
      foreach my $entry (@lines) {
        if ( substr( $entry, 0, 15 ) eq "***************" ) {
          print("<HR>");
        } else {
	  &formatLine( "$entry" );
	  if ( "$compareType" eq "context" ) {
	    print("\n");
	  }
        }
      }
      print("</PRE>");
    } elsif ( "$compareType" eq "table" ) {
      my $tableColor = "#EEEEEE";
      print("<TABLE>
              <TR><TD><CENTER><H2>old: $first</H2></TD><TD><CENTER><H2>new: $last</H2></TD></TR>
              <TR><TD VALIGN=top BGCOLOR=$tableColor>");
      foreach my $entry (@lines) {
        if ( substr( $entry, 0, 15 ) eq "***************" ) {
	  print("</TD></TR><TR><TD VALIGN=top BGCOLOR=$tableColor>");
	} elsif ( substr( $entry, 0, 3 ) eq "***" ) {
	  print("<PRE><B>$entry</B>\n");
	} elsif ( substr( $entry, 0, 3 ) eq "---" ) {
          print("</TD><TD VALIGN=top BGCOLOR=$tableColor><PRE><B>$entry</B>\n");
	} else {
	  my $length = length($entry);
	  if ( $length > 85 ) {
	    # knip de melding op in 2 delen (zonder rekening te houden met spaties e.d..
	    my $part2 = substr( $entry, 80);
	    $entry = substr( $entry, 0, 80 );
	    $entry = "$entry ....<BR>.... $part2";
	  }
	  &formatLine( "$entry" );
	  #print(" ($length)\n");
	  print("\n");
	}
      }
      print("</TD></TR></TABLE>");
    }
  }
}

sub printDiffForm {
  my $directory = "@_[0]";
  my $first = "@_[1]";
  my $last = "@_[2]";
  my $type = "@_[3]";
  my $numLines = "@_[4]";
  print("<FORM method=post Action=$httpScriptName?$tool+reDiff>
      Run diff: 
      <INPUT TYPE=hidden NAME=first VALUE=$first>
      <INPUT TYPE=hidden NAME=last VALUE=$last>
      <INPUT TYPE=hidden NAME=directory VALUE=$directory>
      table <INPUT TYPE=radio NAME=type VALUE=table CHECKED>
      / context<INPUT TYPE=radio NAME=type VALUE=context>
      Context size: <INPUT NAME=numLines VALUE=$numLines TYPE=text SIZE=2>
      <INPUT TYPE=submit Value=\"Compare\">
      </FORM>");
}

sub formatLine {
  my $entry = "@_[0]";
  my $fontColor;
  if (( substr( $entry, 0, 3 ) eq "---" ) or ( substr( $entry, 0, 3 ) eq "***" )) {
    $fontColor = "#9900cc";
  } elsif ( substr( $entry, 0, 1 ) eq "+" ) {
    $fontColor = "green";
  } elsif ( substr( $entry, 0, 1 ) eq "-" ) {
    $fontColor = "red";
  } elsif ( substr( $entry, 0, 1 ) eq "!" ) {
    $fontColor = "blue";
  } else {
    $fontColor = "#333333";
  }
  print("<FONT COLOR=$fontColor>$entry</FONT>");
}

sub listDir {
  my $dirPath = "@_[0]";
  my $sort = "@_[1]";
  my $subDir = "@_[2]";
  my $workDir = $fileDir{ $dirPath };
  my $dirName = $dirName{ $dirPath };
  if ( "$subDir" ne "" ) {
    $workDir = "$fileDir{ $dirPath }/$subDir";
  }
# print("dirPath=$dirPath, workDir=$workDir, dirName=$dirName<HR>");
  if ( $dirPath eq "none" ) {
    print("Oops, no directory found to list.");
  } elsif ( ! -d $workDir ) {
    print("<H3>Oops, the directory for \"$dirName\" not found.</H3>");
    printDebug("0", "workDir=$workDir");
  } else {
    print("<H3>$dirName</H3>");
    print("<FORM method=post Action=$httpScriptName?$tool+grep$dirPath+$subDir>
             <INPUT NAME=searchString Size=60 TYPE=text>
	     <INPUT TYPE=submit Value=\"Search\">");
    if ( "$dirPath" eq "DevConfigsHistory" ) {
      print(" / <A HREF=$httpScriptName?$tool+comp$dirPath>Compare all</A>");
    }
    print("</FORM>");
    if ( "$editFile{ $dirPath }" ne "no" ) {
      print("<FORM method=post Action=$httpScriptName?$tool+edit$dirPath+new+$subDir>
	       <INPUT NAME=fileName Size=60 TYPE=text>
	       <INPUT TYPE=submit Value=\"Add file\">
             </FORM>");
    }
    if ( "$uploadFile{ $dirPath }" eq "yes" ) {
       print("<FORM method=post Action=$httpScriptName?$tool+upld$dirPath+$subDir ENCTYPE=\"multipart/form-data\">
                <INPUT TYPE=\"file\" NAME=\"uploadfile\" Size=60>
                <INPUT TYPE=\"submit\" NAME=\"Submit\" VALUE=\"Send file\">
              </FORM>");
    }
    print("<BR><TABLE BORDER=0 CELLPADDING=5>
           <TR>
	     <TD>Num</TD>
	     <TD></TD>
	     <TD><A HREF=$httpScriptName?$tool+list$dirPath+date+$subDir>Last updated</A></TD>
	     <TD>Size</TD>
	     <TD><A HREF=$httpScriptName?$tool+list$dirPath+name+$subDir>Filename</A></TD>
	     <FORM method=post Action=$httpScriptName?$tool+diff$dirPath+$subDir>
           ");
    if ( "$cmpFile{ $dirPath }" eq "yes" ) {
      print("<TD><INPUT TYPE=submit Value=\"Diff\"></TD>");
      if ( "$subDir" ne "" ) {
        $sort = "date";
      }
    } else {
      print("<TD></TD>");
    }
    print("</TR>");
    chdir("$workDir");
#   print("<TR><TD>subDir=$subDir</TD></TR>");
    my @dirList = <*>;
    if ( "$sort" eq "date" ) {
      my @entries;
      foreach my $entry (@dirList) {
        my $time = (stat $entry)[9];
        splice @entries, @entries, 0, "$time $entry"; #Opbouwen array met datum num plus filename.
      }
      @entries = reverse(sort(@entries));
      @dirList = "";
      foreach my $info (@entries) {
        my ( $dummy, $entry ) = split(/ /, $info);
	splice @dirList, @dirList, 0, "$entry";
      }
    }
    my $num = 1;
    my $first = "no";
    foreach my $entry (@dirList) {
      my $workFile = "$workDir/$entry";
      my $time = (stat $workFile)[9];
      my $size = (stat $workFile)[7];
      my $dateString = printDate($time,"yyyymmdd");
      my $timeString = printDate($time,"hhmmss");
      my $delString = "";
      if (( -w "$workFile" ) and ( -f "$workFile" )){
        $delString = "<A HREF=$httpScriptName?$tool+rem-$dirPath+$entry+$subDir>
	  <IMG ALT=\"Remove file.\" SRC=/sipman3/gifs/database_delete.png BORDER=0></A>";
      }
      my $header = "<TR BGCOLOR=#EEEEEE><TD ALIGN=right>$num</TD><TD>$delString</TD><TD>$dateString $timeString</TD><TD ALIGN=right>$size</TD>";
      if ( "$entry" eq "" ) {
        my $dummy;
      } elsif ( ! -r "$workFile" ) {
        print("$header<TD>$entry</TD><TD>not readable.</TD>");
        $num++;
      } elsif ( -d "$workFile" ) {
        print("$header<TD>$entry</TD>
	       <TD><A HREF=$httpScriptName?$tool+list$dirPath+name+$entry>directory</A></TD>");
        $num++;
      } elsif ( $size eq 0 ) {
        print("$header<TD>$entry</TD><TD>empty</TD>");
        $num++;
      } elsif ( -r "$workFile" ) {
        print("$header<TD><A HREF=$httpScriptName?$tool+type$dirPath+$entry+$subDir>$entry</A></TD>");
        if ( -w "$workFile" ) {
          print("<TD>");
	  if ( "$editFile{ $dirPath }" ne "no" ) {
	    print("<A HREF=$httpScriptName?$tool+edit$dirPath+$entry+$subDir>
	           <IMG SRC=/sipman3/gifs/page_edit.png BORDER=0></A>");
          } else {
            print("<CENTER><INPUT TYPE=checkbox NAME=$entry VALUE=yes>");
          }
	  print("</TD>");
          $num++;
	}
      } else {
        print("$header<TD>$entry</TD><TD>not readable</TD>");
        $num++;
      }
      print("</TR>");
    }
    if ( $exportDir { $dirPath } eq "yes" ) {
      print("<TR><TD></TD><TD COLSPAN=5 ALIGN=right><A HREF=$httpScriptName?$tool+gzip$dirPath>Archive</A></TD></TR>");
    }
    print("</TABLE>");
  }
}

sub remFile {
  my $mainDir = "@_[0]";
  my $fileName= "@_[1]";
  my $subDir = "@_[2]";
  my $workDir;
  if ( "$subDir" eq "" ) {
    $workDir = $fileDir{ $mainDir };
  } else {
    $workDir = "$fileDir{ $mainDir }/$subDir";
  }
  my $workFile = "$workDir/$fileName";
  printDebug("0", "Removing $workFile.");
  if ( -w $workFile ) {
    unlink( $workFile );
    if ( ! -f $workFile ) {
      print("File $fileName removed.");
    } else {
      print("oops, could not remove file $fileName in $mainDir.");
    }
  }
  print("<HR>");
  listDir( $mainDir, "date", $subDir );
}

sub grepDir {
  my $mainDir = "@_[0]";
  my $subDir = "@_[1]";
  my $workDir;
  if ( "$subDir" eq "" ) {
    $workDir = $fileDir{ $mainDir };
  } else {
    $workDir = "$fileDir{ $mainDir }/$subDir";
  }
  my $searchString = param('searchString');
  print("Searching for \"$searchString\" in $mainDir/$subDir ($workDir).<HR>");
  chdir( $workDir );
  print("<TABLE>");
  #system(" grep -ir \"$searchString\" * ");
  my @lines = ` grep -ir \"$searchString\" * `;
  foreach my $info (@lines) {
    my ( $fileInfo, $string ) = split(':', $info, 2);
    my ($filename, $directory);
    if ( "$subDir" eq "" ) {
      ( $directory, $filename ) = split('/', $fileInfo);
#     print("<TR><TD>..$fileInfo, d=$directory, f=$filename..</TD></TR>");
      if ( "$filename" eq "" ) {
        # if the file is not in a sub-dir.
        $filename = $directory;
	$directory = "";
      }
    } else {
      $filename = $fileInfo;
      $directory = $subDir;
    }
    print("<TR><TD><A HREF=$httpScriptName?$tool+type$mainDir+$filename+$directory>$filename</A></TD>
               <TD>$string</TD></TR>");
  }
  print("</TABLE>");
}

sub dispFile {
  my $mainDir = "@_[0]";
  my $fileName= "@_[1]";
  my $subDir = "@_[2]";
  my $workDir;
  if ( "$subDir" eq "" ) {
    $workDir = $fileDir{ $mainDir };
  } else {
    $workDir = "$fileDir{ $mainDir }/$subDir";
  }
  my $workFile = "$workDir/$fileName";
  #print("workFile=$workFile<HR>");
  print("<B>$fileName</B><HR>");
  my $fileType = `file $workFile`;
  my ( $dummy, $type1, $type2, $rest ) = split(' ', $fileType, 4);
  print("($type1 $type2 $rest) last $SIMparam{'SIMcatMaxFileLines'} lines displayed.<BR>\n<TABLE><TR><TD><PRE>");
  if (( substr($type2,0,4) eq "text" ) or ( "$type1" eq "ASCII" ) or ( "$type1" eq "data" ) or ( "$type1" eq "ISO-8859" )
        or ( "$type1" eq "UTF-8" ) or ( "$type1" eq "Assembler" )) {
    system(" cat $workFile | tail -n $SIMparam{'SIMcatMaxFileLines'} ");
  } elsif ( "$type1" eq "gzip" ) {
    system(" gunzip -c $workFile | tail -n $SIMparam{'SIMcatMaxFileLines'} ");
  } else {
    print("Type is $type1 $type2 $rest, not processing....");
  }
  print("</PRE></TD></TR></TABLE>");
}

sub gzipDir {
  my $mainDir = "@_[0]";
  my $workDir = $fileDir{ $mainDir };
  if ( ! -d $workDir ) {
    print("Oops, no workdir for $mainDir.");
  } elsif ( ! -d $systemHtml ) {
    print("Oops, no workdir for $systemHtml.");
  } else {
    system(" rm -fr $systemHtml/gzip-* ");
    my $random = int(rand(1000000));
    my $outDir = "$systemHtml/gzip-$remoteUser-$random";
    chdir( $workDir );
    mkdir( $outDir );
    if ( ! -d $outDir ) {
      print("Oops, could not create random directory.");
    } else {
      print("Creating tar.gz file for $mainDir<HR>Archiving: ");
      system(" tar -cvf $outDir/$mainDir.tar * ");
      print(" gzipping... ");
      system(" gzip $outDir/$mainDir.tar ");
      print("<HR>Get your file
        <A HREF=/$SIMparam{'SIMsystemHtmlHttp'}/gzip-$remoteUser-$random/$mainDir.tar.gz>$mainDir.tar.gz</A> here...
      ");
    }
  }
}

sub updFile {
  my $mainDir = "@_[0]";
  my $fileName= "@_[1]";
  my $subDir = "@_[2]";
  my $inputWidth = "170";
  my $numLines = "30";
  my $workDir;
  if ( "$subDir" eq "" ) {
    $workDir = $fileDir{ $mainDir };
  } else {
    $workDir = "$fileDir{ $mainDir }/$subDir";
  }
  if ( $fileName eq "new" ) {
    $fileName = param('fileName');
    $fileName = testNameStrict( $fileName, "email" );
    print(" touch $workDir/$fileName \n");
    system(" touch $workDir/$fileName ");
  }
  my $update = param("update");
  my $note = param("note");
  # replace CR-LF with LF for further processing
  $note =~ s/\015\012/\012/g;
  my $workFile = "$workDir/$fileName";
  if ( "$update" eq "yes" ) {
    open(OUT, ">$workFile") || die "cannot create $workFile: $!";
    print OUT "$note";
    close OUT;
  }
# print("updFile: mainDir=$mainDir, fileName=$fileName, subDir=$subDir, workFile=$workFile update=$update<HR>");
  if ( -w $workFile ) {
    print("<H3>Updating $fileName</H3>");
    print("
         <FORM method=post Action=$httpScriptName?$tool+edit$mainDir+$fileName+$subDir>
	 <INPUT NAME=update VALUE=\"yes\" TYPE=hidden>
         <INPUT TYPE=submit Value=Update><BR>
         <TEXTAREA NAME=\"note\" ROWS=$numLines COLS=$inputWidth>");
    catFile( $workFile );
    print("</TEXTAREA>
           <BR><INPUT TYPE=submit Value=Update>
           </FORM>
          ");
  }
}

sub uploadFile {
  my $mainDir = "@_[0]";
  my $subDir = "@_[1]";
  my $fileName = param("uploadfile");
  $fileName =~ s/.*[\/\\](.*)/$1/;
  my $dispName;
  my $workDir;
  if ( "$subDir" eq "" ) {
    $workDir = $fileDir{ $mainDir };
    $dispName = "$fileName";
  } else {
    $workDir = "$fileDir{ $mainDir }/$subDir";
    $dispName = "$subDir/$fileName";
  }
  if ( ! -d $workDir ) {
    print("Oops, directory $subDir not found...");
  } elsif  ( "$fileName" eq "" ) {
    print("uploadFile: Oops, no workable filename found..."); 
  } else {
    print("Uploading file $dispName.<BR>");    
    my $upload_filehandle = upload("uploadfile");
    open( UPLOADFILE, ">$workDir/$fileName" ) || die ("Oops, could not open $workDir/$fileName for writing.");
    while ( <$upload_filehandle> ) {
      print UPLOADFILE;
    }
    close UPLOADFILE;
    print("Setting file <B>$dispName</B> readable...<BR>");
    system(" chmod a+r $workDir/$fileName ");
  }
  listDir( $mainDir, "name", $subDir );
}
# ------------------------------------- Main ---------------------------------------

print("<FONT COLOR=#666666>");
printMenu("file2","line", $tool, $action, $option1);
print("</FONT></TD></TR></TABLE><CENTER>");

my $workDir = substr($action,4);
$action = substr($action,0,4);
# print("action=$action, workDir=$workDir, option1=$option1, option2=$option2<HR>");
if ( "$action" eq "list" ) {
  listDir( $workDir, $option1, $option2, $option3 );
} elsif ( "$action" eq "edit" ) {
  updFile( $workDir, $option1, $option2, $option3 );
} elsif ( "$action" eq "type" ) {
  dispFile( $workDir, $option1, $option2, $option3 );
} elsif ( "$action" eq "rem-" ) {
  remFile( $workDir, $option1, $option2, $option3 );
} elsif ( "$action" eq "grep" ) {
  grepDir( $workDir, $option1, $option2, $option3 );
} elsif ( "$action" eq "diff" ) {
  diffDir( $workDir, $option1, $option2, $option3 );
} elsif ( "$action" eq "reDi" ) {
  runCompare; # parameters are in form.
} elsif ( "$action" eq "comp" ) {
  compareAll( $workDir );
} elsif ( "$action" eq "gzip" ) {
  gzipDir( $workDir );
} elsif ( "$action" eq "upld" ) {
  uploadFile( $workDir, $option1, $option2, $option3 );
} else {
  print("<TABLE>");
  printMenu("file2","table", $tool, $action, $option1);
  print("</TABLE>");
}
